<!-- 费用科目 -->
<template>
  <div class="expense">
    <!-- 受试者 -->
    <s-table

      ref="table"
      rowKey="id"
      :columns="columns"
      bordered
      :loading="loading"
      :data="loadData"
    >
      <!-- 表头 start -->
      <template slot="title">
        <div style="display: flex; justify-content: space-between">
          <div>
            <a-radio-group
              v-model="queryParam.type"
              default-value="1"
              button-style="solid"
              @change="handleRadio()"
            >
              <a-radio-button :value="1" >{{ $t('all.autotext1096') }}</a-radio-button>
              <a-radio-button :value="2" >{{ $t('all.autotext446') }}</a-radio-button>
            </a-radio-group>
          </div>
          <div style="display: flex;">
            <a-button
              type="primary"
              icon="plus"
              @click="activeAdd()"
              :disabled="$store.state.user.project.status === 3"
              v-if="editable"
            >
              {{ $t('all.autotext409') }}
            </a-button>
            <a-button
              v-if="editable"
              icon="download"
              style="margin:0 20px"
              :disabled="$store.state.user.project.status === 3"
              @click="downloadTemplate"
            >
              {{ $t('all.autotext626') }}
            </a-button>
            <a-upload
              v-if="editable"
              ref="import"
              accept=".xlsx,.xlsm"
              name="file"
              list-type="picture"
              :before-upload="beforeUploadSite"
              :preview-file="clickImport"
            >
              <a-button type="dashed" :disabled="$store.state.user.project.status === 3">{{ $t('all.autotext990') }}</a-button>
            </a-upload>
            <a-button
              style="margin-left: 20px"
              type="button"
              icon="download"
              v-if="editable"
              @click="clickExport"
            >
              {{ $t('all.autotext1014') }}
            </a-button>
          </div>
        </div>
      </template>
      <!-- 是否默认 -->
      <span slot="status" slot-scope="text, record">
        {{ record.status | enumValueByKey($const.EXPENSE__CURRENT_STATUS) }}
      </span>
      <template slot="stages" slot-scope="text, record">
        <div style="width:120px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
          <a-tooltip v-if="record.stages" placement="topLeft">
            <template slot="title">
              <div v-for="(item, i) in record.stages.split(';')" :key="i">{{ item }}</div>
            </template>
            {{ record.stages }}
          </a-tooltip>
        </div>
      </template>
      <span slot="amt" slot-scope="text, record">
        <span v-if="record.amt === 0">{{ $t('all.autotext1429') }}</span>
        <span v-else>{{ record.amt | formatAmount }}</span>
      </span>
      <!-- 审批资料默认 -->
      <span slot="apv" slot-scope="text, record">
        {{ record.apv | enumValueByKey($const.APPROVAL_FILE) }}
      </span>
      <!-- 是否默认 end-->

      <!-- 操作区 start -->
      <template slot="operation" slot-scope="text, record" v-if="$store.state.user.project.status !== 3">
        <template v-if="editable">
          <a @click="activeEdit(record)">{{ $t('all.autotext919') }}</a>
          <a-divider type="vertical" />
          <a v-if="record.status !== 1" @click="switchStatus(record, 1)">{{ $t('all.autotext307') }}</a>
          <a @click="switchStatus(record, 0)" v-if="record.status === 1 ">{{ $t('all.autotext567') }}</a>
          <a-divider
            type="vertical"
            v-if="queryParam.type == 2  && record.defaulted == 1 "
          />
          <a
            @click="setCenter(record)"
            v-if="queryParam.type == 2  && record.defaulted == 1 "
          >{{ $t('all.autotext1370') }}</a>
        </template>
      </template>
      <!-- 操作区 end -->
    </s-table>
    <!-- 新增弹窗 -->
    <addExpense
      v-model="visible"
      :queryParam="queryParam"
      @refresh="$refs.table.refresh(1)"
      :data="curr"
      :configId="configId"
    />
    <!-- 中心配置弹窗 -->
    <setCenter :visible.sync="setVisible" :item="itemRecord" :configId="configId"/>
  </div>
</template>

<script>
import { getList, toggleStatus, expenseImport, expenseExport, apiGetExportsTemplate } from '@/api/project/configItem/cost'
import { exportBlob, getFileNameByResponse } from '@/utils/util'
import { buildPaginationObj } from '@/components/Table'
import addExpense from './addExpense'
import setCenter from './setCenter'

export default {
  components: { addExpense, setCenter },
  props: {
    editable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      configId: '',
      queryParam: {
        type: 1, // 1：研究者   2：受试者
        proId: '' // 项目Id
      },
      curr: {},
      tableData: [], // 表单数据
      visible: false, // 新增弹框标识
      confirmLoading: false,
      loading: false,
      loadData: parameter => {
        if ((this.queryParam.type === 1) ||
          (this.queryParam.type === 2)) {
          return getList(Object.assign(parameter, { ...this.queryParam, configId: this.configId })).then(res => {
            return res
          })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      setVisible: false,
      itemRecord: ''
    }
  },
  computed: {
    columns () {
      let res = [
        {
          title: this.$t('all.autotext334'),
          width: '100px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: this.$t('all.autotext1278'),
          dataIndex: 'applyType'
        },
        {
          title: this.$t('all.autotext750'),
          dataIndex: 'amt',
          scopedSlots: { customRender: 'amt' }
        },
        {
          title: this.$t('all.autotext1103'),
          dataIndex: 'apv',
          scopedSlots: { customRender: 'apv' }
        },
        {
          title: this.$t('all.autotext983'),
          dataIndex: 'remark'
        },
        {
          title: this.$t('all.autotext1466'),
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ]
      if (this.queryParam.type === 2) {
        res = [
          ...res.slice(0, 2),
          {
            title: this.$t('all.autotext507'),
            dataIndex: 'ptsTypeName'
          },
          ...res.slice(2, 3),
          {
            title: this.$t('all.autotext1297'),
            dataIndex: 'stages',
            scopedSlots: { customRender: 'stages' }
          },
          ...res.slice(3)
        ]
      }
      return res
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.queryParam.proId = parseInt(pd)
    }
    // if (this.$auth('PROJECT.PROJECT_EXPENSE_RESEARCHER')) this.queryParam.type = 1
    // else if (this.$auth('PROJECT.PROJECT_EXPENSE_PATIENT')) this.queryParam.type = 2
    this.configId = this.$route.query.configId
  },
  methods: {
    // 受试人列表
    getList (params = {}) {
      this.loading = true
      getList({ ...this.page, ...params, configId: this.configId })
        .then(res => {
          this.tableData = res.content
          this.pagination.total = res.totalCount
          this.pagination.current = res.pageNumber
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    downloadTemplate () {
      if (this.queryParam.type === this.$const.COMMON_ROLE_TYPE.TESTEE.value) {
        this.downloadSubjectTemplate()
      }
      if (this.queryParam.type === this.$const.COMMON_ROLE_TYPE.RESEARCHER.value) {
        this.downloadResearchTemplate()
      }
    },
    downloadSubjectTemplate () {
      const params = {
        proId: this.queryParam.proId,
        configId: this.configId
      }
      return apiGetExportsTemplate(params).then(res => {
        const fileName = getFileNameByResponse(res.headers)
        exportBlob(fileName, res.data)
      })
    },
    downloadResearchTemplate () {
      const url = this.$options.filters.dealImageUrl(this.$const.TEMPLATE_PATH.EXPENSE)
      window.open(url, '_self')
    },
    // 开始新增
    activeAdd () {
      this.curr = {}
      this.visible = true
    },
    // 开始编辑
    activeEdit (record) {
      const obj = record
      delete obj.createTime // 去除掉多余字段
      delete obj.modifyTime
      this.visible = true
      this.curr = { ...record, defaulted: !!record.defaulted, apv: !!record.apv }
    },
    // 切换人员回调
    handleRadio () {
      this.loadData(this.queryParam)
      this.$refs.table.refresh(true)
    },
    // 启用禁用操作
    switchStatus (record, status) {
      // 编辑
      toggleStatus({
        id: record.id,
        applyType: record.applyType,
        amt: record.amt,
        apv: record.apv,
        defaulted: record.defaulted,
        remark: record.remark,
        type: record.type,
        ptsTypeIdDesc: record.ptsTypeName,
        visitStagesDesc: record.stages,
        status,
        configId: this.configId
      }).then(res => {
        this.$message.success(this.$t('all.autotext470'))
        this.$refs.table.refresh(true)
      })
    },
    beforeUploadSite (file) {
      return false
    },
    // 点击导入
    clickImport (file) {
      const params = new FormData()
      params.append('file', file)
      params.append('proId', this.queryParam.proId)
      params.append('type', this.queryParam.type)
      params.append('configId', this.configId)
      return expenseImport(params).then(res => {
        this.$notification.success({
          message: file.name,
          description: this.$t('all.autotext946')
        })
      }).finally(() => {
        this.$refs.import.sFileList = []
        this.$refs.table.refresh(true)
      })
    },
    // 点击导出
    clickExport () {
      const exportParams = { proId: this.queryParam.proId, type: this.queryParam.type, configId: this.configId }
      expenseExport(exportParams).then(res => {
        exportBlob(this.$t('all.autotext1507') + '.xlsx', res.data)
      })
    },
    setCenter (item) {
      this.setVisible = true
      this.itemRecord = item
    }
  }
}
</script>
